package com.bdzt.beidoubox.fragment;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bdzt.beidoubox.R;
import com.bdzt.beidoubox.activity.CompassActivity;
import com.bdzt.beidoubox.utils.L;
import com.bdzt.beidoubox.utils.T;

import java.math.BigDecimal;

import static android.content.Context.LOCATION_SERVICE;
import static android.content.Context.SENSOR_SERVICE;

/**
 * Created by 、默 on 3/28/2017.
 */

public class HomeFragment extends Fragment implements SensorEventListener {
    private Context context;
    //传感器管理器
    private SensorManager mSensorManager;
    //恒定加速度传感器
    private Sensor mAccelerometer;
    //磁场传感器
    private Sensor mMagneticField;
    //传感器事件监听
    private LocationManager mLocationManager;
    private String mLocationProvider;// 位置提供者名称，GPS设备还是网络

    private float[] mAccelerometerValues = new float[3];
    private float[] mMagneticFieldValues = new float[3];
    private float[] mValues = new float[3];
    private float[] mMatrix = new float[9];
    private float mCurrentDegree = 0f;
    private ImageView rl_needleBack;
    private TextView tv_homeDirection, tv_homeLongitude, tv_homeLatitude, tv_homeHeight;
    private String bearing;
    private Button button;
    private BluetoothAdapter bluetoothAdapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mMagneticField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        initLocationService();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view);
        if (mAccelerometer == null || mMagneticField == null) {
            T.showShort(context, "本机没有磁力计或加速度计o(︶︿︶)o ");
        }

        return view;
    }

    private void initView(View view) {
        rl_needleBack = (ImageView) view.findViewById(R.id.rl_needleBack);
        tv_homeHeight = (TextView) view.findViewById(R.id.tv_homeHeight);
        tv_homeDirection = (TextView) view.findViewById(R.id.tv_homeDirection);
        tv_homeLongitude = (TextView) view.findViewById(R.id.tv_homeLongitude);
        button = (Button) view.findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!bluetoothAdapter.isEnabled()){
                    T.showShort(context,"请先打开蓝牙设备！");
                    return;
                }else {
                    T.showShort(context,"发送蓝牙指令！");
                }
            }
        });
        tv_homeLatitude = (TextView) view.findViewById(R.id.tv_homeLatitude);
        view.findViewById(R.id.rl_compass).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, CompassActivity.class));
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter==null){
            T.showShort(context,"本机暂不支持蓝牙设备！");
        }
        registerService();
    }

    private void registerService() {
        registerSensorService();

        updateLocationService();
    }

    private void registerSensorService() {
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.registerListener(this, mMagneticField, SensorManager.SENSOR_DELAY_NORMAL);
    }

    private void updateLocationService() {
        if (!checkLocationPermission()) {
            // mTvCoord.setText(R.string.check_location_permission);
            return;
        }

        if (mLocationProvider != null) {
            updateLocation(mLocationManager.getLastKnownLocation(mLocationProvider));
            mLocationManager.requestLocationUpdates(mLocationProvider, 5000, 10, mLocationListener);// 5秒或者距离变化10米时更新一次地理位置
        } else {
            //  mTvCoord.setText(R.string.cannot_get_location);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        unregister();

    }

    private void unregister() {
        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this);
        }

        if (mLocationManager != null) {
            if (!checkLocationPermission()) {
                return;
            }
            mLocationManager.removeUpdates(mLocationListener);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregister();
    }

    LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateLocation(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            if (status != LocationProvider.OUT_OF_SERVICE) {
                if (!checkLocationPermission()) {
                    //  mTvCoord.setText(R.string.check_location_permission);
                    return;
                }
                updateLocation(mLocationManager.getLastKnownLocation(mLocationProvider));
            } else {
                // mTvCoord.setText(R.string.check_location_permission);
            }
        }


        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    private void updateLocation(Location location) {
        L.i("location = " + location);
        if (null == location) {
            // mTvCoord.setText(getString(R.string.cannot_get_location));
            // mTvAltitude.setVisibility(View.GONE);
        } else {
            //mTvAltitude.setVisibility(View.VISIBLE);
            StringBuilder sb = new StringBuilder();
            double longitude = location.getLongitude();
            double latitude = location.getLatitude();
            //高度
            double altitude = location.getAltitude();
            tv_homeLatitude.setText("纬度:" + new BigDecimal((double) latitude).setScale(5, 4).floatValue());
            tv_homeLongitude.setText("经度:" + new BigDecimal((double) longitude).setScale(5, 4).floatValue());
            tv_homeHeight.setText("当前海拔:" + altitude + "m");

        }

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            mAccelerometerValues = sensorEvent.values;
        }
        if (sensorEvent.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            mMagneticFieldValues = sensorEvent.values;
        }

        //调用getRotaionMatrix获得变换矩阵mMatrix[]
        SensorManager.getRotationMatrix(mMatrix, null, mAccelerometerValues, mMagneticFieldValues);
        SensorManager.getOrientation(mMatrix, mValues);
        //经过SensorManager.getOrientation(R, values);得到的values值为弧度
        //values[0]  ：azimuth 方向角，但用（磁场+加速度）得到的数据范围是（-180～180）,也就是说，0表示正北，90表示正东，180/-180表示正南，-90表示正西。
        // 而直接通过方向感应器数据范围是（0～359）360/0表示正北，90表示正东，180表示正南，270表示正西。
        float degree = (float) Math.toDegrees(mValues[0]);
        changeOrientation(degree);
        RotateAnimation ra = new RotateAnimation(mCurrentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        ra.setDuration(500);
        ra.setFillAfter(true);
        rl_needleBack.startAnimation(ra);
        mCurrentDegree = -degree;
    }

    private void changeOrientation(float degree) {
        int temp = 0;

        if (degree>=0){
            temp=(int)degree;
        }else {
           temp=(int)360+(int)degree;
        }
        //方位
        if (temp <= 10 || temp >= 350) {
            bearing = "N" + temp + "°";
        } else if (temp <= 80) {
            bearing = "EN" + temp + "°";
        } else if (temp <= 100) {
            bearing = "E" + temp + "°";
        } else if (temp <= 170) {
            bearing = "ES" + temp + "°";
        } else if (temp <= 190) {
            bearing = "S" + temp + "°";
        } else if (temp <= 260) {
            bearing = "WS" + temp + "°";
        } else if (temp <= 280) {
            bearing = "W" + temp + "°";
        } else if (temp <= 350) {
            bearing = "WN" + temp + "°";
        }
        tv_homeDirection.setText(bearing);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    // 设置指南针图片的动画效果
    private void setAnimation(float degree) {
        RotateAnimation ra = new RotateAnimation(mCurrentDegree, -degree, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        ra.setDuration(200);
        ra.setFillAfter(true);
        rl_needleBack.startAnimation(ra);
    }

    private void initLocationService() {
        mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();// 条件对象，即指定条件过滤获得LocationProvider
        criteria.setAccuracy(Criteria.ACCURACY_FINE);// 较高精度
        criteria.setAltitudeRequired(true);// 是否需要高度信息
        criteria.setBearingRequired(true);// 是否需要方向信息
        criteria.setCostAllowed(true);// 是否产生费用
        criteria.setPowerRequirement(Criteria.POWER_LOW);// 设置低电耗
        mLocationProvider = mLocationManager.getBestProvider(criteria, true);// 获取条件最好的Provider,若没有权限，mLocationProvider 为null
        L.i("mLocationProvider = " + mLocationProvider);
    }

    /**
     * 适配android 6.0 检查权限
     */
    private boolean checkLocationPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            return (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) ==
                            PackageManager.PERMISSION_GRANTED);
        }

        return true;

    }
}